package org.qiyu.live.im.core.server.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

import static org.qiyu.live.im.constants.ImConstants.DEFAULT_MAGIC;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-06
 * Time: 20:49
 */
public class TcpImDecoder extends ByteToMessageDecoder {

    private final int BASIC_LEN = 2 + 4 + 4;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        //body的基本校验
        if(byteBuf.readableBytes() >= BASIC_LEN) {
            // 魔数的校验
            if(DEFAULT_MAGIC != byteBuf.readShort()) {
                ctx.close();
                return;
            }
            // 读取code
            int code = byteBuf.readInt();
            // 读取len
            int len = byteBuf.readInt();
            if(byteBuf.readableBytes() < len) {
                ctx.close();
                return;
            }
            byte[] body = new byte[len];
            byteBuf.readBytes(body);
            ImMsg msg = new ImMsg();
            msg.setMagic(DEFAULT_MAGIC);
            msg.setCode(code);
            msg.setLen(len);
            msg.setBody(body);
            // 加到out中,这样下游的处理器就能够读取到这个ImMsg对象了
            out.add(msg);
        }
    }
}